import { Button, Input, message, Form } from 'antd';
import { connect } from 'dva';
import type { CurrentUser } from '@/pages/UserList/components/data';
import styles from './BaseView.less';
import UploadAvatar from '@/components/UploadAvatar';
import { updateUser } from '@/services/user';

const FormItem = Form.Item;

const BaseView = (props) => {
  const { currentUser, dispatch } = props;
  const [form] = Form.useForm();
  const handleSubmit = () => {
    form
      .validateFields()
      .then(async (fieldsValue) => {
        const res = await updateUser({
          ...fieldsValue,
          role: currentUser.role,
          id: currentUser.ID,
        });
        if (res.success) {
          if (dispatch) {
            dispatch({
              type: 'user/fetchCurrent',
              payload: { id: currentUser.ID },
            });
          }
          message.success('修改成功');
        } else {
          message.success('修改失败,请重试');
        }
      })
      .catch(() => {});
  };

  return (
    <Form
      initialValues={{
        username: currentUser.username,
        phone_number: currentUser.phone_number,
        avatar: currentUser.avatar,
      }}
      form={form}
      layout="vertical"
      hideRequiredMark
    >
      <div className={styles.baseView}>
        <div className={styles.right}>
          <Form.Item
            className={styles.avatarBox}
            name="avatar"
            getValueFromEvent={(e) => {
              return e.response.url;
            }}
          >
            <UploadAvatar forValue="avatar" />
          </Form.Item>
          <FormItem
            name="username"
            label="用户名"
            rules={[
              {
                required: true,
                message: '请输入用户名',
              },
            ]}
          >
            <Input />
          </FormItem>
          <FormItem label="电话" name="phone_number">
            <Input />
          </FormItem>
          <Button type="primary" onClick={handleSubmit}>
            更新
          </Button>
        </div>
      </div>
    </Form>
  );
};
export default connect(({ user }: { user: { currentUser: CurrentUser } }) => ({
  currentUser: user.currentUser,
}))(BaseView);
